package com.developer.fans.upgrader;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageParser;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.coocaa.x.framework.utils.LogUtils;
import com.developer.fans.CrackApplication;
import com.skyworth.webSDK.webservice.tcappstore.StoreApkInfo;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import static com.skyworth.framework.skysdk.util.SdCardChecker.isSDCardAvaiable;

/**
 * Created by lu on 15-8-11.
 */
public class AppStoreUpgrader {
    public static class AppStoreUpgradeInfo {
        public boolean hasUpgrade = false;
        public String name;
        public String versionName;
        public int versionCode;
        public long size;
        public String upgradeLog;
        public String url;
    }

    public static interface AppStoreUpgraderListener {
        void onUpgradeInfoReturn(AppStoreUpgradeInfo info);

        void onUpgradeDownloadStart();

        void onUpgradeDownloadProcess(int percent);

        void onUpgradeDownloadError();

        void onUpgradeDownloadFinish(String apk_file);
    }

    private AppStoreUpgraderListener listener = null;
    private Thread checkThread = null;

    private Downloader.LiteUpgradeDownloaderListener downloaderListener = new Downloader.LiteUpgradeDownloaderListener() {
        @Override
        public void onStart() {
            if (listener != null)
                listener.onUpgradeDownloadStart();
        }

        @Override
        public void onProgress(int percent, long downloaded_length, long file_length) {
            if (listener != null)
                listener.onUpgradeDownloadProcess(percent);
        }

        @Override
        public void onError() {
            if (listener != null)
                listener.onUpgradeDownloadError();
        }

        @Override
        public void onSuccess(String apk_file) {
            if (listener != null)
                listener.onUpgradeDownloadFinish(apk_file);
        }

        @Override
        public void onCancel() {
        }
    };

    private static AppStoreUpgrader instance = new AppStoreUpgrader();

    public static AppStoreUpgrader getInstance() {
        return instance;
    }

    private AppStoreUpgrader() {
        Downloader.getInstance().setListener(downloaderListener);
    }

    public void setAppStoreUpgraderListener(AppStoreUpgraderListener l) {
        listener = l;
    }

    public synchronized boolean startCheck() {
        if (checkThread == null) {
            checkThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        AppStoreUpgradeInfo info = getUpgradeInfo();
                        listener.onUpgradeInfoReturn(info);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    checkThread = null;
                }
            });
            checkThread.start();
            return true;
        }
        return false;
    }

    public synchronized void startUpgrade(AppStoreUpgradeInfo info) {
        if (info != null)//&& info.hasUpgrade)
            Downloader.getInstance().start("appstore_update.apk", info.url);
    }

    private AppStoreUpgradeInfo getUpgradeInfo() {
        AppStoreUpgradeInfo info = null;
        try {
            StoreApkInfo apkinfo = null;
            String channel = CrackApplication.getAppStoreInfo().device_channel;
            apkinfo = CrackApplication.getAppStoreService().getStoreApkInfo("Tianci");
            if (apkinfo != null) {
                String j = JSONObject.toJSONString(apkinfo);
                Log.i("upgrade", "apkinfo:" + j);
                try {//apkinfo.verCode
                    if (Integer.valueOf(999999999) > CrackApplication.getAppStoreInfo().versionCode) {
                        info = new AppStoreUpgradeInfo();
                        info.versionCode = Integer.valueOf(apkinfo.verCode);
                        info.versionName = apkinfo.verName;
                        info.name = apkinfo.appName;
                        info.size = 0;
                        info.upgradeLog = apkinfo.updateInfo;
                        info.url = apkinfo.apkDownUrl;
                        info.hasUpgrade = true;
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return info;
    }

    private int getApkPreferInstallLocation(String file) {
        int installlocation = 0;
        try {
            PackageParser.PackageLite pkg = null;
            if (Build.VERSION.SDK_INT < 21) {
                Method staticMethod = PackageParser.class.getDeclaredMethod("parsePackageLite",
                        new Class[]{String.class, int.class});
                pkg = (PackageParser.PackageLite) staticMethod.invoke(null, new Object[]{
                        file, 0});
            } else {
                Method staticMethod = PackageParser.class.getDeclaredMethod("parsePackageLite",
                        new Class[]{File.class, int.class});
                pkg = (PackageParser.PackageLite) staticMethod.invoke(null, new Object[]{
                        new File(file), 0});
            }
            if (pkg != null)
                installlocation = pkg.installLocation;
            Runtime.getRuntime().gc();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return installlocation;
    }

    private static final int INSTALL_LOCATION_UNSPECIFIED = -1;
    private static final int INSTALL_LOCATION_AUTO = 0;
    private static final int INSTALL_LOCATION_INTERNAL_ONLY = 1;
    private static final int INSTALL_LOCATION_PREFER_EXTERNAL = 2;

    private void installWithPackageInstaller(String apkfile) {
        try {
            Uri uri = Uri.fromFile(new File(apkfile));
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("SKYWORTH_HIDE_FLAG_PACKAGENAME", CrackApplication.getContext().getPackageName());

            int preferlocation = getApkPreferInstallLocation(apkfile);
            LogUtils.d("HHHH", "preferlocation:" + preferlocation);
            switch (preferlocation) {
                case INSTALL_LOCATION_INTERNAL_ONLY:
                    intent.putExtra("APP_INSTALL_LOCATION", 1);
                    break;
                case INSTALL_LOCATION_PREFER_EXTERNAL:
                case INSTALL_LOCATION_AUTO:
                case INSTALL_LOCATION_UNSPECIFIED:
                    if (isSDCardAvaiable()) {
                        intent.putExtra("APP_INSTALL_LOCATION", 2);
                    } else {
                        intent.putExtra("APP_INSTALL_LOCATION", 0);
                    }
                    break;
            }
            CrackApplication.getContext().startActivity(intent);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void installWithAutoInstaller(String apkfile) {
        try {
            Intent intent = new Intent("coocaa.intent.action.AUTOINSTALLER");
            intent.putExtra("apkfilepath", apkfile);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            CrackApplication.getContext().startActivity(intent);
        } catch (Exception e) {
            installWithPackageInstaller(apkfile);
        }
    }

}
